package cn.player.media.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import cn.player.R;
import cn.player.media.entity.VideoInfo;
import cn.player.media.view.StarMediaController;
import cntv.player.core.util.LogUtil;
import cntv.player.core.util.Utils;
import cntv.player.engine.Const;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnCompletionListener;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnErrorListener;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnPreparedListener;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnSurfaceListener;
import tv.danmaku.ijk.media.player.widget.BaseMediaController.OnVideoPlayListener;
import tv.danmaku.ijk.media.player.widget.IRenderView;
import tv.danmaku.ijk.media.player.widget.IjkVideoView;

public class MediaPlayVFragment extends BaseFragment {

    private static final String TAG = "zl";
    /**
     * 点播视频当前播放的位置
     */
    public long currentPosition;

    /**
     * MediaPlayVFragment是否调用了onPaused暂停播放了
     */
    private boolean isPaused;

    //fragment界面
//	private RelativeLayout mRlRoot;
    private IjkVideoView mVideoView;
    private ProgressBar pbProgressBar;

    /**
     * 传入播放器的videoInfo实体
     */
    private VideoInfo videoInfo;

    /**
     * 播放器最终播放地址，传入播放器底层的地址: mVideoView.setVideoPath(finalVideoUrl)
     */
    private String finalVideoUrl;

    //播放器相关监听器 VideoView暴露
    private OnPreparedListener mOnPreparedListener;
    //	private OnInfoListener mOnInfoListener;
    private OnCompletionListener mOnCompletionListener;
    private OnErrorListener mOnErrorListener;
    private OnSurfaceListener mOnSurfaceListener;

    //播放器相关监听器MediaController暴露
    private OnVideoPlayListener mOnVideoPlayListener;
    private StarMediaController.OnHiddenListener mOnHiddenListener;
    private StarMediaController.OnShownListener mOnShownListener;

    // controller视图
    private StarMediaController mMediaController;

    //播放器相关信息变量
    /**
     * 当前播放码率
     */
    private int currentRate;
    /**
     * 是否播放成功,加载状态条消失
     */
    private boolean isPlaySuccess;
    /**
     * 点播视频是否播放完成
     */
    private boolean isPlayComplete;
    /**
     * 是否点击了暂停按钮，视频处于暂停播放状态
     */
    private boolean isVideoPasued;
    /**
     * surfaceview是否创建成功
     */
    private boolean isSufaceCreated;

    private long startPlayTime;

    private TelephonyManager mTelephonyManager;
    private PhoneStateListener mPhoneStateListener;

    private OnPlayerListener mOnPlayerListener;

    private List<String> mVideoList;
    private int mCurrentPlayPosition;

    /**
     * 获取MediaPlayFrament实例
     *
     * @param videoInfo
     * @return
     */
    public static MediaPlayVFragment newInstance(VideoInfo videoInfo) {
        MediaPlayVFragment mpFrag = new MediaPlayVFragment();
        Bundle args = new Bundle();
        args.putSerializable(VideoInfo.class.getName(), videoInfo);
        mpFrag.setArguments(args);
        return mpFrag;
    }


    @Override
    protected int setContentLayout() {
        return R.layout.player_frag_star_layout;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
//		LogUtil.i(TAG,"MediaPlayVFragment onAttach");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//		LogUtil.i(TAG,"MediaPlayVFragment onCreate");

        mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
//		LogUtil.i(TAG,"MediaPlayVFragment onCreateView");
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        LogUtil.d(TAG, "MediaPlayVFragment onSaveInstanceState()");
        if (getActivity() == null) {
            LogUtil.d(TAG, "MediaPlayVFragment onSaveInstanceState() getActivity()==null...");
            return;
        }
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//		LogUtil.i(TAG,"MediaPlayVFragment onActivityCreated");

        if (getArguments() != null) {
            videoInfo = (VideoInfo) getArguments().getSerializable(VideoInfo.class.getName());
        }

        if (videoInfo == null) {
            LogUtil.i(TAG, "MediaPlayVFragment onActivityCreated() getArguments().getSerializable(VideoInfo.class.getName()) is null....");
            playError(Const.ERROR_PLAY_EXCEPTION, R.string.error_get_play_info_null);
            return;
        }

        setVideoListeners();

        initMediaController();

        listeningPhoneState();


        setVideoList();

        normalPlay(videoInfo.getDetailUrl());
    }


    private void setVideoList(){
        mVideoList = new ArrayList<>();
        mVideoList.add("http://videos.xingliaoapp.com/videos/146858045512172.m3u8");
        mVideoList.add("http://videos.xingliaoapp.com/videos/97441468404971.m3u8");
        mVideoList.add("http://videos.xingliaoapp.com/videos/114681468403938.m3u8");
        mVideoList.add("http://videos.xingliaoapp.com/videos/115731468570754.m3u8");
        mVideoList.add("http://videos.xingliaoapp.com/videos/132081468489089.m3u8");
        mVideoList.add("http://videos.xingliaoapp.com/videos/114681468470280.m3u8");
    }

    /**
     * 设置videoview的各种监听器
     */
    private void setVideoListeners() {
        // mVideoView.setOnBufferingUpdateListener(mOnBufferingUpdateListener);//在MediaContrller中已经监听了
//		mVideoView.setOnInfoListener(mOnInfoListener);//在MediaContrller中已经监听了
        mVideoView.setOnPreparedListener(mOnPreparedListener);
        mVideoView.setOnCompletionListener(mOnCompletionListener);
        mVideoView.setOnErrorListener(mOnErrorListener);
        mVideoView.setOnSurfaceListener(mOnSurfaceListener);
    }

    /**
     * 初始化MediaController并提前设置,
     * 播放器未成功播放时也予显示
     */
    private void initMediaController() {
        if (mMediaController == null) {
            mMediaController = new StarMediaController(mContext);
        }

        mMediaController.initialize();
        mMediaController.setOnVideoPlayListener(mOnVideoPlayListener);
        mMediaController.setOnHiddenListener(mOnHiddenListener);
        mMediaController.setOnShownListener(mOnShownListener);

        mVideoView.setMediaController(mMediaController);
        mVideoView.setVideoLayout(IRenderView.AR_ASPECT_FILL_PARENT);
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        LogUtil.i(TAG, "MediaPlayVFragment onConfigurationChanged");
    }


    @Override
    protected void findViews(View rootView) {
        super.findViews(rootView);

//		mRlRoot = (RelativeLayout) rootView.findViewById(R.id.rl_root_video);
        mVideoView = (IjkVideoView) rootView.findViewById(R.id.cmv_surfaceView);
        pbProgressBar = (ProgressBar) rootView.findViewById(R.id.pb_progressBar);
    }

    @Override
    protected void setListensers() {
        super.setListensers();
        mOnVideoPlayListener = new OnVideoPlayListener() {

            @Override
            public void onVideoLoading() {
                pbProgressBar.setVisibility(View.VISIBLE);
                if (!Utils.isNetConneted(mContext) && videoInfo.getFlag() != Const.VODCACHE) {
                    LogUtil.i(TAG, "MediaPlayVFragment onVideoLoading() net is disconnected....");
                    playError(Const.ERROR_NET_EXCEPTION, R.string.error_net_exception);
                }
            }

            @Override
            public void onVideoPlay() {
                long nowTime = System.currentTimeMillis();
                LogUtil.i(TAG, "视频地址缓冲时长：" + (nowTime - startPlayTime));

                isPlaySuccess = true;
                isPlayComplete = false;
//                setLoadingLayout();

                if (mOnPlayerListener != null) {
                    mOnPlayerListener.onPlayStart();
                }
                if (isVideoPasued || isPaused) {
                    LogUtil.i(TAG, "mVideoView.pause()");
                    mVideoView.pause();
                } else {
                    pbProgressBar.setVisibility(View.GONE);
                }
            }

            @Override
            public void onVideoPlayComplete() {
//				LogUtil.i(TAG,"onVideoPlayComplete....onVideoPlayComplete");
                if (mOnPlayerListener != null) {
                    mOnPlayerListener.onPlayComplete();
                }
            }
        };
        mOnPreparedListener = new OnPreparedListener() {

            @Override
            public void onPrepared(IMediaPlayer mp) {
//				LogUtil.e(TAG, "MediaPlayVFragment:CntvPlayer videoview  onPrepared .....");
                mVideoView.start();

            }
        };
        mOnCompletionListener = new OnCompletionListener() {

            @Override
            public void onCompletion(IMediaPlayer mp) {
                LogUtil.i(TAG, "mOnCompletionListener....mOnCompletionListener");
                currentPosition = 0;
                isPlayComplete = true;
                playNextVideo();
                if (mOnPlayerListener != null) {
                    mOnPlayerListener.onPlayComplete();
                }
            }
        };

        mOnErrorListener = new OnErrorListener() {
            @Override
            public boolean onError(IMediaPlayer mp, int what, int extra) {
                LogUtil.i(TAG, "MediaPlayVFragment onErrorListener....");
                stopPlayer(false);
                return true;
            }
        };
        mOnSurfaceListener = new OnSurfaceListener() {


            @Override
            public void onSurfaceCreate() {
                isSufaceCreated = true;

                pbProgressBar.setVisibility(View.VISIBLE);//显示正在加载
                LogUtil.i("zl", "MediaPlayVFragment onSurfaceCreate finalVideoUrl = " + finalVideoUrl);
                if (!TextUtils.isEmpty(finalVideoUrl)) {
                    normalPlay(finalVideoUrl);
                }
            }

            @Override
            public void onSurfaceDestroyed() {
                isSufaceCreated = false;
                stopPlayer(false);
            }
        };

        mOnHiddenListener = new StarMediaController.OnHiddenListener() {

            @Override
            public void onHidden() {
            }
        };

        mOnShownListener = new StarMediaController.OnShownListener() {

            @Override
            public void onShown() {
            }
        };
    }

    /**
     * 将fragment移除
     */
    public void removeSelf() {
        FragmentTransaction mFragTransaction = getFragTran();
        mFragTransaction.remove(this);
        mFragTransaction.commitAllowingStateLoss();
    }

    /**
     * 获取FragmentTransaction
     *
     * @return
     */
    public FragmentTransaction getFragTran() {
        FragmentTransaction mFragTransaction = null;
        if (getParentFragment() == null) {
            mFragTransaction = ((FragmentActivity) mActivity).getSupportFragmentManager().beginTransaction();
        } else {
            mFragTransaction = getParentFragment().getChildFragmentManager().beginTransaction();
        }
        return mFragTransaction;
    }

    /**
     * 弹框提示播放错误
     */
    private void playError(int errNo, int errMsgId) {
        if (getActivity() == null) {
            return;
        }
        playError(errNo, getString(errMsgId));
    }

    /**
     * 弹框提示播放错误
     */
    private void playError(int errNo, String errMsg) {
        if (getActivity() == null) {
            return;
        }
        if (mOnPlayerListener != null) {
            mOnPlayerListener.onPlayError(errNo, errMsg);
        } else {
            removeSelf();
            errMsg = TextUtils.isEmpty(errMsg) ? getString(R.string.error_exception) : errMsg;
            new AlertDialog.Builder(mContext).setTitle("提示").setMessage(errMsg)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            mActivity.finish();
                        }
                    }).show();
        }
    }
    /***********************start 播放器播放相关方法 start*************************/

    /**
     * 正常播放,高清或者标清
     *
     * @param path
     */
    private void normalPlay(String path) {
        if (TextUtils.isEmpty(path)) {
            LogUtil.i(TAG, "MediaPlayVFragment normalPlay() path is null....");
            playError(Const.ERROR_PLAY_EXCEPTION, R.string.error_path_null);
            return;
        }
        finalVideoUrl = path;
        LogUtil.i(TAG, "MediaPlayVFragment normalPlay() isSufaceCreated = " + isSufaceCreated + ",finalVideoUrl = " + finalVideoUrl);
        currentRate = videoInfo.getRate();
        if (isSufaceCreated) {
            startPlayTime = System.currentTimeMillis();//用来记录播放缓冲时间
            mVideoView.setVideoPath(finalVideoUrl);
            if (currentPosition != 0) {
                mVideoView.seekTo(currentPosition);
            }
        }
    }

    /**
     * 通过videoUrl开始播放video
     *
     * @param videoUrl
     */
    public void playVideo(String videoUrl) {
        stopPlayer(true);
        if(mMediaController != null){
            mMediaController.initialize();
        }
        finalVideoUrl = videoUrl;
        normalPlay(finalVideoUrl);
    }

    private void playNextVideo(){
        mCurrentPlayPosition++;
        if(mCurrentPlayPosition < mVideoList.size()){
            playVideo(mVideoList.get(mCurrentPlayPosition));
        }
    }



    /**
     * 释放播放器
     *
     * @param playStart 释放播放器后再次播放时是否从头播放
     */
    private void stopPlayer(boolean playStart) {
        isPlaySuccess = false;
        if (mVideoView != null) {
            currentPosition = playStart ? 0 : mVideoView.getCurrentPosition();
            mVideoView.pause();
            mVideoView.stopPlayback();
        }
    }

    /**********************end 播放器播放相关方法 end******************************/
    /*******************
     * start 外部调用相关接口和相关方法 start
     ************************/
    public interface OnPlayerListener {
        /**
         * 播放缓冲完成
         */
        void onPlayStart();

        /**
         * 播放暂停改变
         *
         * @param isPaused
         */
        void onPlayPauseChanged(boolean isPaused);

        /**
         * 播放错误
         *
         * @param errorNo
         * @param errMsg
         */
        void onPlayError(int errorNo, String errMsg);

        /**
         * 播放完成
         */
        void onPlayComplete();
    }

    public interface OnShareListener {
        void onShare(VideoInfo videoInfo);
    }

    /**
     * 设置播放监听
     *
     * @param l
     */
    public void setOnPlayerListener(OnPlayerListener l) {
        this.mOnPlayerListener = l;
    }

    /**
     * 获取MediaController
     *
     * @return
     */
    public StarMediaController getMediaController() {
        return mMediaController;
    }


    /**
     * 判断MediaPlayer是否暂停
     *
     * @return
     */
    public boolean isVideoPaused() {
        return isVideoPasued;
    }

    /*******************end 外部调用相关接口和相关方法 end**********************/

    /**
     * 监听来电
     */
    private void listeningPhoneState() {
        mPhoneStateListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                if (state == TelephonyManager.CALL_STATE_IDLE) {
                    if (mVideoView != null && !isPaused) {
                        mVideoView.start();
                    }
                } else {
                    if (mVideoView != null) {
                        mVideoView.pause();
                    }
                }
            }
        };
        mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    }

    /**
     * 取消来电监听
     */
    private void cancelPhoneStateListen() {
        mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
    }

    @Override
    public void onStart() {
        super.onStart();
//		LogUtil.i(TAG,"MediaPlayVFragment onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtil.i(TAG, "MediaPlayVFragment onResume");
        isPaused = false;
        if (isSufaceCreated && !isVideoPasued && mVideoView != null) {
            mVideoView.start();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
//		LogUtil.i(TAG,"MediaPlayVFragment onPause");
        isPaused = true;
        if (mVideoView != null) {
            mVideoView.pause();
            currentPosition = mVideoView.getCurrentPosition();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
//		LogUtil.i(TAG,"MediaPlayVFragment onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//		LogUtil.i(TAG,"MediaPlayVFragment onDestroyView");

        isPlaySuccess = false;
        if (mMediaController != null) {
            mMediaController.hide();
        }
        if (mVideoView != null) {
            mVideoView.stopPlayback();
        }
        cancelPhoneStateListen();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//		LogUtil.i(TAG,"MediaPlayVFragment onDestroy");

        stopPlayer(true);


        mOnPreparedListener = null;
        mVideoView.setOnPreparedListener(null);
        mOnCompletionListener = null;
        mVideoView.setOnCompletionListener(null);
        mOnErrorListener = null;
        mVideoView.setOnErrorListener(null);
        mOnSurfaceListener = null;
        mVideoView.setOnSurfaceListener(null);

        mOnVideoPlayListener = null;
        mMediaController.setOnVideoPlayListener(null);
        mOnHiddenListener = null;
        mMediaController.setOnHiddenListener(null);
        mOnShownListener = null;
        mMediaController.setOnShownListener(null);
        mMediaController = null;
        mVideoView.setMediaController(null);

        rootView = null;
        mVideoView = null;
    }

    @Override
    public void onDetach() {
        super.onDetach();
//		LogUtil.i(TAG,"MediaPlayVFragment onDetach");
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
